package com.doupi.partner.rpc.interceptor;

import com.doupi.partner.util.HttpRequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.*;
import java.io.IOException;

/**
 * 日志拦截器，拦截后添加日志MDC
 */
public class RpcFilter implements Filter {
	private static final String LOGGER_USER = "USER";
	private static final String LOGGER_IP = "OP";
	private static final String ERROR_MESSAGE_TIP = "出错啦！~~~";
	private static final Logger logger = LoggerFactory.getLogger(RpcFilter.class);

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			MDC.put(LOGGER_USER, "RPC");
			String ip = HttpRequestUtils.getClientIp(request);
			MDC.put(LOGGER_IP, ip);
			chain.doFilter(request, response);
		} catch (Exception e) {
			logger.error(ERROR_MESSAGE_TIP, e);
			throw e;
		} finally {
			try {
				MDC.remove(LOGGER_USER);
				MDC.remove(LOGGER_IP);
			} catch (Exception e) {
				logger.error(ERROR_MESSAGE_TIP, e);
			}
		}
	}

	@Override
	public void destroy() {
	}
}
